<?php
declare (strict_types=1);

namespace app\controller\backend;

use app\model\Admin;
use app\model\AdminMenu;
use app\model\Role;
use app\service\RoleService;
use app\validate\RoleValidate;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Lang;


class RoleController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(Role $role): \think\response\Json
    {
        $where = [
            'seller_id' => $this->admin['seller_id'],
        ];

        $roleList = $role->getRoleList($where);
        return json($roleList);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Role $role): \think\response\Json
    {
        if (request()->isPost()) {
            $param = request()->only(['title', 'status']);
            // 数据验证
            try {
                validate(RoleValidate::class)->scene('save')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];

            $role->saveUnique(['seller_id' => $param['seller_id'], 'title' => $param['title']], lang('角色已经存在'));

            $res = $role->addRole($param);
            return json($res);
        }
        return jsonReturn(-3, Lang::get('请求方法错误'));
    }

    /**
     * 显示指定的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Role $role): \think\response\Json
    {

        $id = (int)input('id');
        if (!$id) {
            return jsonReturn(-1,  Lang::get('角色ID不能为空'));
        }
        $where = [
            'id' => $id,
            'seller_id' => $this->admin['seller_id']
        ];
        $res = $role->getRole($where, ['website']);
        if (!empty($res['data']['kid_auth'])) {
            $res['data']['auth'] = explode(',', $res['data']['kid_auth']);
        } else {
            $res['data']['auth'] = [];
        }
        $res['data']['website_id'] = array_column($res['data']['website']->toArray(), 'id');
        return json($res);
    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     * @throws \app\exception\ModelEmptyException
     */
    public function update(Role $role): \think\response\Json
    {
        if (request()->isPost()) {
            $param = input('post.');
            try {
                validate(RoleValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            if ($param['group'] == 1) {
                jsonReturn(-2,  Lang::get('系统默认角色,不能编辑'));
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $roleInfo = $role->getRole($where)['data'];
            if (empty($roleInfo)) {
                return jsonReturn(-3,  Lang::get('角色不存在'));
            }
            $role->updateUnique(['seller_id' => $this->admin['seller_id'], 'title' => $param['title']], $param['id'], lang('角色已经存在'));
            if (!empty($param['auth'])) {
                $len = count($param['auth']);
                foreach ($param['auth'] as $key => $val) {
                    if ($val == 2) {
                        break;
                    }
                    if ($len == $key + 1) {
                        $param['auth'][] = 2;
                    }
                }
                $param['auth'] = implode(',', $param['auth']);
            }
            $roleInfo->website()->detach();
            $roleInfo->website()->attach($param['website_id']);
            unset($param['website_id']);
            $param['kid_auth'] = implode(',', $param['kid_auth']);
            $res = $role->updateRole($where, $param);
            return json($res);
        }
        return jsonReturn(-3, Lang::get('请求方法错误'));
    }

    /**
     * 删除指定资源
     *
     * @throws \app\exception\ModelException
     */
    public function delete(Role $role): \think\response\Json
    {
        if (request()->isPost()) {
            $id = (int)input('id');
            if (!$id) {
                return jsonReturn(-1,  Lang::get('Id不能为空'));
            }
            if ($id == 1) {
                return jsonReturn(-2,  Lang::get('系统默认角色，不能删除'));
            }
            $where = [
                'id' => $id,
                'seller_id' => $this->admin['seller_id']
            ];
            $res = $role->delRole($where);
            return json($res);
        }
        return jsonReturn(-3, Lang::get('请求方法错误'));
    }


    /**
     * @throws \app\exception\ModelException
     */
    public function getAuth(AdminMenu $AdminMenu): \think\response\Json
    {
        $auth = $AdminMenu->getAllAdminMenu(['seller_id' => $this->admin['seller_id'], 'status' => 1])['data']->toArray();
        $auth = generate($auth);
        return jsonReturn(0, Lang::get('成功'), $auth);
    }

    public function getMenuAndUpdateAuth()
    {
        $adminId = $this->admin['uid'];
        $res = RoleService::getMenuAndUpdateAuth($adminId);

        return json($res);
    }
}
